package com.code2roc.fastboot.framework.security;

import com.alibaba.fastjson.JSON;
import com.code2roc.fastboot.framework.extra.enums.SystemErrorCodeEnum;
import com.code2roc.fastboot.framework.model.Result;
import com.code2roc.fastboot.framework.extra.systemload.SystemLoaderUtil;
import com.code2roc.fastboot.framework.util.BeanUtil;
import org.springframework.core.Ordered;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class CORSFilter implements Filter, Ordered {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            HttpServletResponse res = (HttpServletResponse) response;
            res.addHeader("Access-Control-Allow-Origin", "*");
            res.addHeader("Access-Control-Allow-Methods", "GET,POST");
            res.addHeader("Access-Control-Allow-Headers", "*");
            res.getWriter().println("ok");
            return;
        }
        if(!SystemLoaderUtil.checkLoaderTag()){
            HttpServletResponse res = (HttpServletResponse) response;
            res.addHeader("Access-Control-Allow-Origin", "*");
            res.addHeader("Access-Control-Allow-Methods", "GET,POST");
            res.addHeader("Access-Control-Allow-Headers", "*");
            Result result =  Result.errorResult().setMsg(SystemErrorCodeEnum.ErrorCode.SystemUnLoader.get_name()).setCode(SystemErrorCodeEnum.ErrorCode.SystemUnLoader.get_value());
            response.getWriter().println(JSON.toJSON(result));
            return;
        }

        SecurityConfig securityConfig = BeanUtil.getBean(SecurityConfig.class);
        List<String> allowList = securityConfig.getAllowedOrigin();
        String allowString = "";
        for (String item : allowList) {
            allowString += item + ",";
        }
        if(allowString.length()>0){
            allowString = allowString.substring(0,allowString.length()-1);
        }
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Origin", allowString);
        res.addHeader("Access-Control-Allow-Methods", "GET,POST");
        res.addHeader("Access-Control-Allow-Headers", "*");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
